<?php

class SystemModel extends BaseModel
{

	/**
	 * Hold an instance of the class
	 * @var
	 */
	private static $_instance = null;

	/**
	 * A private constructor
	 * Prevents direct creation of object
	 */
	private function __construct(){
		$this->_init();
	}


	/**
	 * The singleton method
	 * @return
	 */
	public static function getInstance(){
		if (!self::$_instance instanceof self)
		self::$_instance = new self;

		return self::$_instance;
	}

	public function getOptions(){

		$options = dibi::query("SELECT name, value FROM ".self::TABLE_OPTIONS."")->fetchPairs("name","value");

		if(empty($options)) self::reloadOptions();

		return $options;

	}

	public function setOptionVariable($name, $value){

		if(!self::existsOption($name)) self::addOption($name);

		dibi::query("UPDATE ".self::TABLE_OPTIONS." SET value = ", $value, "WHERE name = %s",$name);

	}

	public function getOptionVariable($name){

		$options = self::getOptions();

		foreach($options as $key=>$value){
			if($key==$name) return $value;
		}

		return false;

	}

	public function addOption($name){

		dibi::query("INSERT INTO ".self::TABLE_OPTIONS." (name) VALUES(%s)", $name);

	}

	public function saveOptions($options){

		foreach($options as $key=>$value){
			self::setOptionVariable($key, $value);
		}

	}

	public function existsOption($name){

		$exists = dibi::query("SELECT name FROM ".self::TABLE_OPTIONS." WHERE name = %s", $name)->fetchSingle();

		return !empty($exists) ? true : false;
	}

	public function reloadOptions(){

		$options = array("sess_exp" => "");

		foreach($options as $key=>$value){
			if(!self::existsOption($key)) self::addOption($key);
		}

	}

	public function getLanguages(){

		return dibi::query("SELECT * FROM ".self::TABLE_LANGUAGES."");

	}

	public function getDefaultLanguage(){

		return dibi::query("SELECT * FROM ".self::TABLE_LANGUAGES." WHERE `default` = %i", 1)->fetchAll();

	}

	public function getLanguage($id_language){

		return dibi::query("SELECT * FROM ".self::TABLE_LANGUAGES." WHERE id_language = %i", $id_language)->fetchAll();

	}
	
	public function getCurrentLanguage(){
		
		return dibi::query("SELECT * FROM ".self::TABLE_LANGUAGES." WHERE id_language = %i", $this->session_web->id_language)->fetchAll();
	}
	
	public function addLanguage($args){
		
		dibi::query("INSERT INTO ".self::TABLE_LANGUAGES."", $args);
		
	}
	
	public function editLanguage($args){
		
		$id_language = $args["id_language"];
		unset($args["id_language"]);
		dibi::query("UPDATE ".self::TABLE_LANGUAGES." SET", $args, "WHERE id_language = %i", $id_language);
		
	}
	
	public function deleteLanguage($id_language){
		
		dibi::query("DELETE FROM ".self::TABLE_LANGUAGES." WHERE id_language = %i", $id_language);
		
	}
	
	public function setLanguage($id_language){

		$this->session->admin_id_language = $id_language;

	}

	public function initLanguage(){

		if(empty($this->session->admin_id_language)){
			$lang = self::getDefaultLanguage();
			self::setLanguage($lang[0]["id_language"]);
		}

	}
	
	public function initLanguageWeb(){

		if(empty($this->session_web->id_language)){
			$lang = self::getDefaultLanguage();
			self::setLanguageWeb($lang[0]["id_language"]);
		}

	}
	
	public function setLanguageWeb($id_language){

		$this->session_web->id_language = $id_language;

	}

	public function saveMenuItem($args = array()){

		if($args["start"]==1){
			dibi::query("UPDATE ".self::TABLE_MENU." SET start = 0 WHERE id_language = %i", $this->session->admin_id_language);
		}

		if($args["parent"] == 0) {
			$args["parent"] = NULL;
			$last = dibi::query("SELECT `order` FROM ".self::TABLE_MENU." WHERE parent IS NULL ORDER BY `order` DESC")->fetchAll();
			$args["depth"] = 0;
		}else{
			$last = dibi::query("SELECT `order`, `depth` FROM ".self::TABLE_MENU." WHERE parent = %i", $args["parent"], "ORDER BY `order` DESC")->fetchAll();
			$parent = dibi::query("SELECT depth FROM ".self::TABLE_MENU." WHERE id_menu = %i", $args["parent"])->fetchAll();
			$args["depth"] = $parent[0]["depth"] + 1;
		}

		// overime zda se zmenil predek, jestli ano prepocitame poradi
		$last_access = dibi::query("SELECT parent FROM ".self::TABLE_MENU." WHERE id_menu = %i", $args["id_menu"])->fetchSingle();

		if($last_access!=$args["parent"] || empty($args["id_menu"])){

			if(empty($last[0]["order"])) $order = 1;
			else $order = $last[0]["order"] + 1;

			$args["order"] = $order;

		}

		if(empty($args["id_menu"])){
			$args["id_language"] = $this->session->admin_id_language;
			dibi::query("INSERT INTO ".self::TABLE_MENU."", $args);
		}else
		dibi::query("UPDATE ".self::TABLE_MENU." SET", $args, "WHERE id_menu = %i", $args["id_menu"]);

	}

	public function getMenuLeaf($parent){

		if($parent==NULL) return dibi::query("SELECT * FROM ".self::TABLE_MENU." WHERE parent IS NULL ORDER BY `order` ASC")->fetchAll();

		return dibi::query("SELECT * FROM ".self::TABLE_MENU." WHERE parent = %i", $parent, "ORDER BY `order` ASC")->fetchAll();

	}

	public function deleteMenuItem($id_menu){

		dibi::query("DELETE FROM ".self::TABLE_MENU." WHERE id_menu = %i", $id_menu);

	}

	public function loadMenuItemById($id_menu){

		return dibi::query("SELECT * FROM ".self::TABLE_MENU." WHERE id_menu = %i", $id_menu)->fetchAll();

	}

	public function getModules(){

		return dibi::dataSource("SELECT * FROM ".self::TABLE_MODULES."");

	}

	public function getUsers(){

		return dibi::query("SELECT * FROM ".self::TABLE_USERS." WHERE role != 'superAdmin'")->fetchAll();

	}

	public function loadModulesFromDir(){

		$modules = array();

		if ($handle = opendir(WWW_DIR . '/app/modules/')) {

			while (false !== ($file = readdir($handle))) {
				if($file != "." && $file != ".."){
					$name = explode(".",$file);
					$modules[]["name"] = $name[0];
				}
			}

			closedir($handle);
		}
		return $modules;

	}

	public function isModulRegistered($presenter){

		$is = dibi::query("SELECT name FROM ".self::TABLE_MODULES." WHERE presenter = %s", $presenter)->fetchAll();

		return empty($is) ? false : true;

	}

	public function registerModule($args){

		dibi::query("INSERT INTO ".self::TABLE_MODULES."", $args);

	}

	public function moduleAddSql($sql){

		dibi::query($sql);

	}

	public function toggleModule($id_module){

		$active = dibi::query("SELECT active FROM ".self::TABLE_MODULES." WHERE id_module = %i", $id_module)->fetchSingle();

		$active = $active == 1 ? 0 : 1;

		dibi::query("UPDATE ".self::TABLE_MODULES." SET active = %i", $active,"WHERE id_module = %i", $id_module);

	}

	public function loadUser($id_user){

		return dibi::query("SELECT * FROM ".self::TABLE_USERS." WHERE id_user = %i", $id_user)->fetchAll();

	}

	public function getMenu($iter = FALSE, $id_menu=FALSE){

		if(!$id_menu) $menu = dibi::query("SELECT menu.*, modules.presenter, modules.params, modules.name AS module_name FROM ".self::TABLE_MENU." AS menu LEFT JOIN ".self::TABLE_MODULES." AS modules USING(id_module) WHERE parent IS NULL AND id_language = %i ORDER BY `order` ASC", $this->session->admin_id_language)->fetchAll();
		else $menu = dibi::query("SELECT menu.*, modules.presenter, modules.params, modules.name AS module_name FROM ".self::TABLE_MENU." AS menu LEFT JOIN ".self::TABLE_MODULES." AS modules USING(id_module) WHERE parent IS NULL AND id_language = %i", $this->session->admin_id_language,"AND id_menu = %i", $id_menu,"ORDER BY `order` ASC")->fetchAll();
		
		foreach($menu as &$m){
			$iterator = "";
			self::getMenuChildrens($m, $iterator, $iter);
		}

		unset($m);

		return $menu;
	}

	public function getMenuWeb($iter = FALSE, $id_menu=FALSE){

		if(!$id_menu) $menu = dibi::query("SELECT menu.*, modules.presenter, modules.params, modules.name AS module_name, lang.default, lang.abbr FROM ".self::TABLE_MENU." AS menu LEFT JOIN ".self::TABLE_MODULES." AS modules USING(id_module) JOIN ".self::TABLE_LANGUAGES." AS lang USING(id_language) WHERE parent IS NULL AND id_language = %i ORDER BY `order` ASC", $this->session_web->id_language)->fetchAll();
		else $menu = dibi::query("SELECT menu.*, modules.presenter, modules.params, modules.name AS module_name, lang.default, lang.abbr FROM ".self::TABLE_MENU." AS menu LEFT JOIN ".self::TABLE_MODULES." AS modules USING(id_module) JOIN ".self::TABLE_LANGUAGES." AS lang USING(id_language) WHERE parent IS NULL AND id_language = %i", $this->session_web->id_language,"AND id_menu = %i", $id_menu,"ORDER BY `order` ASC", $this->session_web->id_language)->fetchAll();

		foreach($menu as &$m){
			$iterator = "";
			self::getMenuChildrens($m, $iterator, $iter);
		}

		unset($m);

		return $menu;
	}

	public function getMenuChildrens(&$parent, &$iterator, &$iter){

		$parent["sub"] = dibi::query("SELECT menu.*, modules.presenter, modules.params, modules.name AS module_name, lang.default, lang.abbr FROM ".self::TABLE_MENU."  AS menu LEFT JOIN ".self::TABLE_MODULES." AS modules USING(id_module) JOIN ".self::TABLE_LANGUAGES." AS lang USING(id_language) WHERE parent = %i", $parent["id_menu"],"ORDER BY `order` ASC")->fetchAll();

		if(!empty($parent["sub"])){

			foreach($parent["sub"] as $s){
				if($iter) $iterator = str_repeat("-", $s["depth"]);
				$s["name"] = $iterator.$s["name"];
				self::getMenuChildrens($s, $iterator, $iter);
			}
		}

	}

	public function getMenuToSelect(){

		$menu = self::getMenu();

		$out = array();

		foreach($menu as $item){
			$iterator = "";
			$out[$item["id_menu"]] = $item["name"];

			if(!empty($item["sub"])){
				self::getSubMenuToSelect($item["sub"], $out, $iterator);
			}

		}

		return $out;
	}

	public function getSubMenuToSelect($sub, &$out, &$iterator){

		
		foreach($sub as $s){
			$iterator = str_repeat("-", $s["depth"]);
			$out[$s["id_menu"]] = $iterator.$s["name"];
			if(!empty($s["sub"])) self::getSubMenuToSelect($s["sub"], $out, $iterator);
		}
	}

	public function getMenuForRouter($admin=FALSE){

		if($admin==false) $menu = self::getMenuWeb();
		else $menu = self::getMenu();

		$out = array();

		foreach($menu as &$item){
			$out[] = $item;

			//$item->name_seo_router = $item["name_seo"];
			$par_name = $item["name_seo"];
			if(!empty($item["sub"])){
				self::getSubMenuForRouter($item["sub"], $out, $par_name);
			}

		}

		return $out;

	}

	public function getSubMenuForRouter($sub, &$out, $par_name){

		if(substr($par_name,0, -1)!="/") $par_name .= "/";

		foreach($sub as $s){
			$s->name_seo_router = $par_name;

			$out[] = $s;
			if(!empty($s["sub"])) self::getSubMenuForRouter($s["sub"], $out, $par_name.$s["name_seo"]);
		}

	}

	public function getMenuItemById($id){

		return dibi::query("SELECT * FROM ".self::TABLE_MENU." WHERE id_menu = %i", $id)->fetchAll();

	}

	public function getMenuItemByname($name){

		return dibi::query("SELECT menu.*, modules.presenter FROM ".self::TABLE_MENU." AS menu LEFT JOIN ".self::TABLE_MODULES." AS modules USING(id_module) WHERE name_seo = %s", $name)->fetchAll();

	}

	public function getModulesToSelect(){

		$modules = self::getModules()->where("active = 1")->select("*");

		$out = array();
		foreach($modules as $module){
			$out[$module["id_module"]] = $module["name"];
		}

		return $out;
	}

	public function saveUser($args){

		dibi::query("INSERT INTO ".self::TABLE_USERS."", $args);

	}

	public function editUser($args){

		dibi::query("UPDATE ".self::TABLE_USERS." SET", $args,"WHERE id_user = %i", $args["id_user"]);

	}

	public function addUser($args){

		dibi::query("INSERT INTO ".self::TABLE_USERS."", $args);

	}

	public function deleteUser($id_user){

		dibi::query("DELETE FROM ".self::TABLE_USERS." WHERE id_user = %i", $id_user);

	}
	
	public function getNavigation(){
		$uri = Environment::getHttpRequest()->uri->path;
		$uri = substr($uri, 1, -1);
		
		$address = explode("/", $uri);
		
		$navigace = array();
		$citac = 0;
		$last = end($address);
		$count = count($address);

		foreach($address as $a){

			$menu = $this->getMenuItemByname($a);
			$addresa .= $a."/";
			if($menu[0]["start"]!=1){
			
			if($citac==0) $menu[0]["name"] = $this->translation["home"];
			$navigace[$citac]["address"] = $last == $a ? "" : $addresa;
			$navigace[$citac]["name"] = $menu[0]["name"]; 
			if(($count == 2 && $menu[0]["start"]==1)){
				$navigace[0]["address"] = "";
			}
			
			$citac++; 
			}
			if(($count == 2 && $menu[0]["start"]==1)){
					$navigace[0]["address"] = "";
			}
		}

		return $navigace;
	}
}

?>